package com.zn.znch.yhp.znchv2.service;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zn.znch.yhp.znchv2.common.HttpUtils;
import com.zn.znch.yhp.znchv2.common.PointDate;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;

@Slf4j
@Component
public class CCService {
//    public static String path = "/home/zd/znch/cc/data";
//    public static String configPath = "/home/zd/znch/cc/config/config.properties";

    ExecutorService executorService = Executors.newFixedThreadPool(20);
    public static String path = "D:/temp/znch/cc/data";
    public static String configPath = "D:/temp/znch/cc/config/config.properties";
    public static int maxLine = 86400;
    private static String URL = "http://132.0.2.36:8721";
    private static String findPoints_addr = "/macs/v1/realtime/read/findPoints";
    private static String writePoint_addr = "/macs/v1/realtime/write/writePoints";
    private static String TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0aWQiOm51bGwsInNpZCI6IiIsImFjY291bnQiOiJaTkNIIiwidHlwZSI6ImFwcCIsInNvdXJjZSI6InRoaXJkIiwiY3JlYXRvciI6ImIxOTA5MDVhLTM5NTAtMTFlZC04YjJhLTUyNTQwMGQ2ZjA3MSJ9.iMUMONae4FPS8NCMPjeYfa_Lnery6Ssg81WszdC_1TM";


    @Scheduled(cron = "10,30,50 * * * * *")
    public void performTask() {
        log.info("更新长吹数据任务开始…………");
        HashMap<String, String> map = null;
        String responseString = new String();
        try {
            HashMap headers = new HashMap<String, String>();
            headers.put("content-type", "application/json");
            headers.put("token", TOKEN);
            String body = getTagString();
            HttpResponse response = HttpUtils.doPost(URL, findPoints_addr, headers, null, body);
            HttpEntity entity = response.getEntity();
            map = new HashMap<>();
            if (entity == null) {
                log.error("接口数据异常：request:{},HttpResponse:{}", body, JSONObject.toJSONString(response));
                return;
            }
            responseString = EntityUtils.toString(entity);
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(responseString);
            JsonNode dataValue = jsonNode.get("data");
            for (int i = 0; i < dataValue.size(); i++) {
                JsonNode node = dataValue.get(i);
                String tag = node.get("tag").asText().toString();
                JsonNode item = node.get("item");
                String value = (item.get("AV") != null ? item.get("AV") : item.get("DV")).toString();
                map.put(tag, value);
            }
        } catch (Exception e) {
            log.error("短吹请求外部接口异常，responseString :{}", responseString);
            log.error("短吹请求外部接口失败：e:{}", e.getMessage());
            return;
        }
        log.info("长吹元数据请求外部接口，responseString :{}", responseString);
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        String sysTime = now.format(formatter);
        //读取
        File directory = new File(path);
        if (!directory.exists()) {
            directory.mkdirs();
        }
        Set<String> fileName = PointDate.hangzeng_wenjiang.keySet();
        //读取配置文件
        //参数格式：HCB11AT001_AM001.csv=0.09252555088362652,23.511458992100607,26185.08827909366,2,0.9918512509956572
        FileInputStream params = null;
        Properties properties = null;
        try {
            params = new FileInputStream(configPath);
            properties = new Properties();
            properties.load(params);
        } catch (Exception e) {
            log.error("长吹配置文件加载失败！Exception:{}",e.getMessage());
        }

        //读取原吹灰记录
        List<Callable<String>> tasks = new ArrayList<>();
        for (String name : fileName) {
            String gsll = map.get("AMECOINFWQ");//给水流量
            String hangzeng = map.get(name);//焓增
            String wenjiang = "0";
            if (PointDate.wenjiangPoint.get(name) != null) {
                String wenjiangKey = PointDate.wenjiangPoint.get(name);
                wenjiang = map.get(wenjiangKey);//温降
            }
            String value = PointDate.hangzeng_wenjiang.get(name);//吹灰标记
            String[] chuihui = value.split(",");
            String chuihuiFlag = "";
            for (int i = 0; i < chuihui.length; i++) {
                String s = map.get(chuihui[i]);
                chuihuiFlag = chuihuiFlag + "_" + s;
            }

            if(null ==  gsll || gsll.isEmpty()){
                continue;
            }

            CCTask task =new CCTask(directory, name, params, sysTime, gsll, hangzeng, wenjiang, chuihuiFlag, properties);
            tasks.add(task);
        }

        HashMap<String,String> result = null;
        try {
            //结果示例：HCB12AT003_AM001_0
            List<Future<String>> futures = executorService.invokeAll(tasks);

            result = new HashMap();
            for (Future<String> future : futures) {
                String[] s = future.get().split(":");
                result.put(s[0],s[1]);
            }
        } catch (Exception e) {
            log.info("长吹批量任务结果获取失败：directory:{};Exception:{}; ",directory,e.getMessage());
        }

        //回写吹灰
        sendChuiHuiNode(result);
        //记录吹灰需求
        writeChuihuiNode(result,fileName,sysTime);
    }

    private void sendChuiHuiNode(HashMap<String, String> result) {
        log.info("长吹结果："+JSONObject.toJSONString(result));
        HashMap headers = new HashMap<String, String>();
        headers.put("content-type", "application/json");
        headers.put("token", TOKEN);
        String writePoint_body = getChuiHuiReqBody();
        //低再
        if("0".equals(result.get("HCB11AT004_AM001")) || "0".equals(result.get("HCB12AT004_AM001"))){
            result.put("HCB11AT004_AM001","0");
        }
        //低过
        if("0".equals(result.get("HCB11AT005_AM001")) || "0".equals(result.get("HCB12AT005_AM001"))){
            result.put("HCB11AT005_AM001","0");
        }
        //二省
        if("0".equals(result.get("HCB11AT006_AM001")) || "0".equals(result.get("HCB12AT006_AM001"))){
            result.put("HCB11AT006_AM001","0");
        }

        for (Map.Entry<String,String> entry:result.entrySet()) {
            String name = entry.getKey();
            String chuihui = entry.getValue();
            name = name.replace("_AM001","")+"_DI";
            writePoint_body = writePoint_body.replace(name,chuihui);
        }
        log.info("长吹吹灰需求下发，请求参数："+writePoint_body);
        String responseString = null;
        try {
            HttpResponse writeResponse = HttpUtils.doPost(URL, writePoint_addr, headers, null, writePoint_body);
            HttpEntity entity = writeResponse.getEntity();
            responseString = EntityUtils.toString(entity);
        } catch (Exception e) {
            log.info("短吹吹灰需求下发失败："+e);
            return;
        }
        log.info(" CCService success 吹灰需求下发结果："+responseString.toString());
    }




    public static void writeChuihuiNode(HashMap<String,String> result,Set<String> fileName,String sysTime){
        //记录吹灰记录
        try {
            String filePath = "D:\\temp\\znch\\cc\\chuihui.csv";
            File file = new File(filePath);
            List<String> data = new ArrayList<>();
            if (file.exists()) {
                //读取历史数据
                FileReader fr = new FileReader(filePath);
                BufferedReader br = new BufferedReader(fr);
                String line = br.readLine();
                while (line != null) {
                    data.add(line);
                    line = br.readLine();
                }
                //删除原文件
                file.delete();
            }
            if (data.size() > maxLine) {
                data.remove(0);
            }
            FileWriter writer = new FileWriter(filePath);
            for (int i = 0; i < data.size(); i++) {
                writer.append(data.get(i));
                writer.append("\n");
            }
            StringBuffer sb = new StringBuffer();
            sb.append(sysTime);
            for (String key : fileName) {
                sb.append(",").append(key).append("_").append(result.get(key));
            }
            sb.append("\n");
            writer.append(sb.toString());
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    private String getTagString() {
        String ss = "{'tags': [{'items': ['AV'], 'namespace': 'unit02', 'tag': 'AMECOINFWQ'}, {'items': ['AV'], 'namespace': 'unit02', 'tag': 'HCB11AT001_AM001'}, {'items': ['AV'], 'namespace': 'unit02', 'tag': 'HCB12AT001_AM001'}, {'items': ['AV'], 'namespace': 'unit02', 'tag': 'HCB11AT002_AM001'}, {'items': ['AV'], 'namespace': 'unit02', 'tag': 'HCB12AT002_AM001'}, {'items': ['AV'], 'namespace': 'unit02', 'tag': 'HCB11AT003_AM001'}, {'items': ['AV'], 'namespace': 'unit02', 'tag': 'HCB11AT003_AM002'}, {'items': ['AV'], 'namespace': 'unit02', 'tag': 'HCB12AT003_AM001'}, {'items': ['AV'], 'namespace': 'unit02', 'tag': 'HCB12AT003_AM002'}, {'items': ['AV'], 'namespace': 'unit02', 'tag': 'HCB11AT004_AM001'}, {'items': ['AV'], 'namespace': 'unit02', 'tag': 'HCB11AT004_AM002'}, {'items': ['AV'], 'namespace': 'unit02', 'tag': 'HCB12AT004_AM001'}, {'items': ['AV'], 'namespace': 'unit02', 'tag': 'HCB12AT004_AM002'}, {'items': ['AV'], 'namespace': 'unit02', 'tag': 'HCB11AT005_AM001'}, {'items': ['AV'], 'namespace': 'unit02', 'tag': 'HCB11AT005_AM002'}, {'items': ['AV'], 'namespace': 'unit02', 'tag': 'HCB12AT005_AM001'}, {'items': ['AV'], 'namespace': 'unit02', 'tag': 'HCB12AT005_AM002'}, {'items': ['AV'], 'namespace': 'unit02', 'tag': 'HCB11AT006_AM001'}, {'items': ['AV'], 'namespace': 'unit02', 'tag': 'HCB11AT006_AM002'}, {'items': ['AV'], 'namespace': 'unit02', 'tag': 'HCB12AT006_AM001'}, {'items': ['AV'], 'namespace': 'unit02', 'tag': 'HCB12AT006_AM002'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB11AT001ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB12AT001ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB11AT002ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB12AT002ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB11AT003ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB12AT003ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB11AT004ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB12AT004ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB11AT005ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB12AT005ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB11AT006ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB12AT006ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB11AT007ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB12AT007ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB11AT008ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB12AT008ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB11AT009ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB12AT009ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB11AT010ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB12AT010ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB11AT011ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB12AT011ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB11AT012ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB12AT012ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB11AT013ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB12AT013ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB11AT014ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB12AT014ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB11AT015ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB12AT015ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB11AT016ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB12AT016ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB11AT017ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB12AT017ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB11AT018ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB12AT018ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB11AT019ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB12AT019ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB11AT020ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB12AT020ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB11AT021ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB12AT021ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB11AT022ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB12AT022ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB11AT023ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB12AT023ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB11AT024ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB12AT024ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB11AT025ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB12AT025ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB11AT026ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB12AT026ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB11AT027ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB12AT027ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB12AT027ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB15AT002ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB15AT003ZO'}, {'items': ['DV'], 'namespace': 'unit02', 'tag': 'HCB15AT004ZO'}]}\n";
        return ss;
    }

    private String getChuiHuiReqBody() {
        return "[{'items': [{'item': 'DI','value': HCB11AT001_DI}],'namespace':'unit02','tag': 'HCB11AT001_ICS'},\n" +
                "{'items': [{'item': 'DI','value': HCB12AT001_DI}],'namespace':'unit02','tag': 'HCB12AT001_ICS'},\n" +
                "{'items': [{'item': 'DI','value': HCB11AT002_DI}],'namespace':'unit02','tag': 'HCB11AT002_ICS'},\n" +
                "{'items': [{'item': 'DI','value': HCB12AT002_DI}],'namespace':'unit02','tag': 'HCB12AT002_ICS'},\n" +
                "{'items': [{'item': 'DI','value': HCB11AT003_DI}],'namespace':'unit02','tag': 'HCB11AT003_ICS'},\n" +
                "{'items': [{'item': 'DI','value': HCB12AT003_DI}],'namespace':'unit02','tag': 'HCB12AT003_ICS'},\n" +
                "{'items': [{'item': 'DI','value': HCB11AT004_DI}],'namespace':'unit02','tag': 'HCB11AT004_ICS'},\n" +
                "{'items': [{'item': 'DI','value': HCB12AT004_DI}],'namespace':'unit02','tag': 'HCB12AT004_ICS'},\n" +
                "{'items': [{'item': 'DI','value': HCB11AT005_DI}],'namespace':'unit02','tag': 'HCB11AT005_ICS'},\n" +
                "{'items': [{'item': 'DI','value': HCB12AT005_DI}],'namespace':'unit02','tag': 'HCB12AT005_ICS'},\n" +
                "{'items': [{'item': 'DI','value': HCB11AT006_DI}],'namespace':'unit02','tag': 'HCB11AT006_ICS'},\n" +
                "{'items': [{'item': 'DI','value': HCB12AT006_DI}],'namespace':'unit02','tag': 'HCB12AT006_ICS'}]";
    }
}
